import React, {PureComponent, Fragment} from 'react';
import {connect} from 'dva';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Table,
  Button,
  InputNumber,
  Popconfirm,
  Tag,
  Modal,
  message,
  Divider,
} from 'antd';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from './Dept.less';

const FormItem = Form.Item;

const CreateForm = Form.create({
  onValuesChange(props, changedFields) {
    props.onModelChange(changedFields);
  },
  mapPropsToFields(props) {
    const {formValues} = props;
    if (formValues) {
      return {
        deptId: Form.createFormField({
          value: formValues.deptId,
        }),
        parentId: Form.createFormField({
          value: formValues.parentId ? formValues.parentId : '0',
        }),
        orderNum: Form.createFormField({
          value: formValues.orderNum,
        }),
        name: Form.createFormField({
          value: formValues.name,
        }),
      };
    }
  },
})(props => {
  const {modalVisible, form, handleAdd, handleModalVisible, modalTitle} = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      handleAdd(fieldsValue);
    });
  };
  return (
    <Modal
      width={820}
      title={modalTitle}
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible()}>
      <FormItem labelCol={{span: 5}} wrapperCol={{span: 15}} label="父节点ID">
        {form.getFieldDecorator('parentId', {
          initialValue: '-1',
          rules: [{required: true, message: '父节点ID不能为空'}],
        })(<Input placeholder="请输入" disabled/>)}
      </FormItem>
      <FormItem labelCol={{span: 5}} wrapperCol={{span: 15}} label="ID">
        {form.getFieldDecorator('deptId', {
          rules: [{required: true, message: 'ID不能为空'}],
        })(<Input placeholder="请输入" disabled={modalTitle === '修改部门'}/>)}
      </FormItem>
      <FormItem labelCol={{span: 5}} wrapperCol={{span: 15}} label="名称">
        {form.getFieldDecorator('name', {
          rules: [{required: true, message: '名称不能为空'}],
        })(<Input placeholder="请输入"/>)}
      </FormItem>

      <FormItem labelCol={{span: 5}} wrapperCol={{span: 15}} label="排序">
        {form.getFieldDecorator('orderNum', {
          initialValue: 10,
        })(
          <InputNumber min={0}/>
        )}
      </FormItem>
    </Modal>
  );
});

@connect(({dept, loading}) => ({
  dept,
  formValues: dept.formValues,
  loading: loading.models.dept,
}))
@Form.create()
export default class Dept extends PureComponent {
  state = {
    modalTitle: '部门管理',
    type: 'add',
    modalVisible: false,
  };

  componentDidMount() {
    this.props.dispatch({
      type: 'dept/fetch',
    });
  }

  handleDeptDelete = record => {
    this.props.dispatch({
      type: 'dept/remove',
      payload: record,
      callback: () => {
        message.success('删除部门成功!');
      },
    });
  };

  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
    });
  }

  handleDeptAdd = flag => {
    this.props.dispatch({
      type: 'dept/new',
      payload: {},
      callback: () => {
        this.setState({
          modalTitle: '新增部门',
          type: 'add',
        });
        this.handleModalVisible(flag)
      },
    });
  };

  handleDeptAddLevel = (flag, parentId) => {
    this.props.dispatch({
      type: 'dept/new',
      payload: {parentId: parentId},
      callback: () => {
        this.setState({
          type: 'add',
          modalTitle: '新增部门',
        });
        this.handleModalVisible(flag)
      },
    });
  };

  handleDeptEdit = (flag, deptId) => {
    this.props.dispatch({
      type: 'dept/get',
      payload: deptId,
      callback: () => {
        this.setState({
          modalTitle: '修改部门',
          type: 'eidt',
        });
        this.handleModalVisible(flag)
      },
    });
  };

  onModelChange = changedFields => {
    this.props.dispatch({
      type: 'dept/change',
      payload: {
        ...changedFields,
      }
    })
  }

  handleAdd = fields => {
    if (this.state.type == 'add') {
      this.props.dispatch({
        type: 'dept/add',
        payload: {
          ...fields,
        },
        callback: () => {
          this.setState({
            modalVisible: false,
          });
          message.success('添加部门成功!');
        },
      });
    } else {
      this.props.dispatch({
        type: 'dept/edit',
        payload: {
          ...fields,
        },
        callback: () => {
          this.setState({
            modalVisible: false,
          });
          message.success('更新部门成功!');
        },
      });
    }
  };

  render() {
    const {dept: {data}, loading, formValues} = this.props;
    const {modalVisible, modalTitle} = this.state;
    const columns = [
      {
        title: 'ID',
        dataIndex: 'id',
      },
      {
        title: '标题',
        dataIndex: 'name',
      },
      {
        title: '排序',
        dataIndex: 'sort',
      },
      {
        title: '操作',
        render: (text, record) => (
          <Fragment>
            <a onClick={() => this.handleDeptEdit(true, record.id)}>编辑</a>
            <Divider type="vertical"/>
            <a onClick={() => this.handleDeptAddLevel(true, record.id)}>下级</a>
            <Divider type="vertical"/>
            <Popconfirm title="是否要删除此行？" onConfirm={() => this.handleDeptDelete(record)}>
              <a>删除</a>
            </Popconfirm>
          </Fragment>
        ),
      },
    ];

    const parentMethods = {
      onModelChange: this.onModelChange,
      handleAdd: this.handleAdd,
      handleModalVisible: this.handleModalVisible,
    };

    return (
      <PageHeaderLayout title="部门管理">
        <Card bordered={false}>
          <div className={styles.dept}>
            <div className={styles.deptOperator}>
              <Button icon="plus" type="primary" onClick={() => this.handleDeptAdd(true)}>
                新建
              </Button>
            </div>
            <Table columns={columns} loading={loading} dataSource={data} pagination={false}/>
          </div>
        </Card>
        <CreateForm modalTitle={modalTitle} formValues={formValues} {...parentMethods}
                    modalVisible={modalVisible}/>
      </PageHeaderLayout>
    );
  }
}
